<?php

namespace app\admin\controller\qingdongams\finance;

use addons\qingdongams\model\Consume as ConsumeModel;
use addons\qingdongams\model\Customer as CustomerModel;
use addons\qingdongams\model\JointFollow;
use app\admin\controller\qingdongams\Base;
use addons\qingdongams\model\Consume;
use addons\qingdongams\model\ConsumeDetail;
use addons\qingdongams\model\Customer;
use addons\qingdongams\model\ExamineRecord;
use addons\qingdongams\model\Staff;

/**
 * 报销管理
 * @icon fa fa-user
 */
class Finance extends Base {
	protected $relationSearch = true;
	protected $searchFields   = 'id,title';
	/**
	 * @var \addons\qingdongams\model\Consume
	 */
	protected $model = null;


	public function _initialize() {
		parent::_initialize();
		$this->model = new Consume();
	}


	/**
	 * 查看
	 */
	public function index() {
		//设置过滤方法
		$this->request->filter(['strip_tags', 'trim']);
		if ($this->request->isAjax()) {
			//如果发送的来源是Selectpage，则转发到Selectpage
			if ($this->request->request('keyField')) {
				return $this->selectpage();
			}
			$condition['consume.check_status'] = ['in',[0,1,2,3]];
			$condition['consume.staff_id'] = ['in',Staff::getMyStaffIds()];
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $createtime = input('createtime','');
            $wheres = [];
            if($createtime && $createtime !='null '){
                $start = date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),1,date("Y")));
                $end = date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("t"),date("Y")));
                $wheres['createtime'] = array('between',array(strtotime($start),strtotime($end)));
            }
            $model=new ConsumeDetail();
            $list = $model->with(['consume'])->where($where)
                ->where($condition)->where($wheres)->order('id desc')->paginate($limit);
            foreach ($list as $k=>&$v){
                $v['staff']=Staff::where(['id'=>$v['consume']['staff_id']])->field('id,img,name,post,mobile')->find();
                $v['customer']=Customer::where(['id'=>$v['consume']['customer_id']])->field('id,name,address')->find();
                $img = array_column($v['imgList'],'url');
                $v->imgs = implode(',',$img);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
		}

		return $this->view->fetch();
	}

    //修改
    public function edit($ids = null) {
        $map['id'] = $ids;
        if ($this->request->isAjax()) {
            $data   = $this->request->post('row/a');
            $result = $this->model->save($data, $map);

            if (!$result) {
                $this->error('修改失败');
            }
            $this->success('修改成功');
        }
        $data = $this->model->where($map)->find();
        $this->view->assign("row", $data);

        return $this->view->fetch();
    }

	//费用详情
	public function detail($ids = null) {
	    // 基本信息
        $row = $this->model->where('id',$ids)->with(['staff','customer'])->find();
        if(empty($row)){
            $this->error('信息不存在');
        }
        $row['detail']= ConsumeDetail::where(['consume_id'=>$ids])->select();
        if ($row['check_status'] == 0 || $row['check_status'] == 1) {
            $row['is_examine'] = ExamineRecord::isExaminse(ExamineRecord::CONSUME_TYPE, $ids);
        } else {
            $row['is_examine'] = 0;
        }
        // 操作记录
        $operations = ExamineRecord::where('relation_id',$ids)->with(['checkStaff'])->select();
        $this->assign('ids',$ids);
        $this->assign('row',$row);
        $this->assign('operations',$operations);
		return $this->view->fetch();
	}

	// 处理参数
	public function operateParasm($data) {
	    $detail_field = ['consume_type','consume_date','consume_money','end_mileage','mileage','file_ids','remark'];
	    $list = [];
	    foreach ($data as $k=>$v) {
            if(in_array($k,$detail_field)){
                foreach ($v as $key=>$val) {
                    $list[$key][$k] = $val;
                }
            }

        }
        return array_values($list);
    }
    //获取联合跟进人
    public function getShowStaff($ids = null)
    {
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        $list = \addons\qingdongams\model\JointFollow::where(['relation_type' => JointFollow::CONSUME_TYPE, 'relation_id' => $ids])->with(['staff'])->paginate($limit);
        $total = $list->total();
        $stfflist = $list->toArray()['data'];
        foreach ($stfflist as $k => $value){
            if ($value['roles'] == 1){
                $stfflist[$k]['is_edit'] = '负责人';
            }else{
                $stfflist[$k]['is_edit'] = $value['is_edit'] == 1?'读写':'只读';
            }
            $stfflist[$k]['roles'] = $value['roles'] == 1?'负责人':'团队成员';
        }
        $result = array("total" => $total, "rows" => $stfflist);

        return json($result);
    }


    public function set_team($ids = null){
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                $id = $params['id'];
                $staff = $params['staff'];
                $model = Consume::get($id);
                if (empty($model)) {
                    $this->error('客户不存在');
                }
                foreach ($staff as $k=>$v) {
                    if ($v['roles'] == 1) {//负责人
                        $find = JointFollow::where(['relation_type' => JointFollow::CONSUME_TYPE,
                            'relation_id' => $id,
                            'roles' => 1
                        ])->find();
                        if($v['id'] != $find['staff_id']){
                            JointFollow::where(['id'=>$find['id']])->update(['staff_id'=>$v['id']]);
                            $model = Consume::get($id);
                        }
                        unset($staff[$k]);
                    }
                }
                JointFollow::where(['relation_type' => JointFollow::CONSUME_TYPE,
                    'relation_id' => $id,
                    'roles' => 2
                ])->delete();

                $show_staff_id = [];
                $show_staff_id[] = $model->staff_id;
                $jointFollow = new JointFollow();
                $add = [];
                $find = JointFollow::where(['relation_type' => JointFollow::CONSUME_TYPE,
                    'relation_id' => $id,
                    'roles' => 1
                ])->find();
                foreach ($staff as $v) {
                    if($v['id'] != $find['staff_id']) {
                        $add[] = [
                            'relation_type' => $jointFollow::CONSUME_TYPE,
                            'relation_id' => $id,
                            'staff_id' => $v['id'],
                            'is_edit' => $v['is_edit'],
                            'roles' => 2,
                        ];
                        $show_staff_id[] = $v['id'];
                    }
                }
                $jointFollow->saveAll($add);
                $model->save(['show_staff_ids' => implode(',', $show_staff_id)]);
                $this->success('编辑成功');
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $list = \addons\qingdongams\model\JointFollow::where(['relation_type' => JointFollow::CONSUME_TYPE, 'relation_id' => $ids,'roles' => 2])->with(['staff'])->select();
        $staffs = Staff::getList();
        $principal = \addons\qingdongams\model\JointFollow::where(['relation_type' => JointFollow::CONSUME_TYPE, 'relation_id' => $ids,'roles' => 1])->with(['staff'])->find();
        $this->assign('staffs', $staffs);
        $this->assign('principal', $principal);
        $this->assign('id',$ids);
        $this->assign('list', $list);
        return $this->view->fetch();
    }

    public function add_team($ids = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if (!$params['staff_id']) {
                $this->error('请选择员工');
            }
            if ($params['is_edit'] == '') {
                $this->error('请选择权限');
            }
            $is_have = \addons\qingdongams\model\JointFollow::where(['relation_type' => JointFollow::CONSUME_TYPE, 'relation_id' => $ids, 'staff_id' => $params['staff_id']])->with(['staff'])->select();
            if ($is_have) {
                $this->error('该员工已存在团队中');
            }
            $info = Staff::get($params['staff_id'])->toArray();
            $info['is_edit'] = $params['is_edit'];
            $this->success('添加成功', '', $info);
        }
        $staffs = Staff::getList();
        $this->assign('staffs', $staffs);
        $this->assign('ids', $ids);
        return $this->view->fetch();
    }

}
